package com.itheima.controller;

import com.itheima.pojo.Goods;
import com.itheima.service.GoodsService;
import com.itheima.utils.HeiMaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/list")
    public String list(Map<String, Object> map) {
        List<Goods> goodsList = goodsService.findAllGoods();
        // log.info(goodsList.toString());
        // goodsList.forEach(s -> log.info(s.getRealPrice()));

        // map.put("debug", "true"); // 调试使用,在网页上显示数据库查询出来的数据
        map.put("goodsList", goodsList);

        return "list";
    }

    @GetMapping("/detail")  // 对于匿名用户这里会创建Session
    public ModelAndView detail(Integer id, HttpSession session) {
        log.info("id = " + id);
        Goods goods = goodsService.findGoodsAndEvaluate(id);

        // 使用Token解决CSRF
        // session.setAttribute("token", String.valueOf(System.currentTimeMillis()));

        // 解决评论富文本XSS攻击
        goods.getComments().forEach(comment -> {
            String content = comment.getContent();
            comment.setContent(HeiMaUtils.htmlWhiteList(content));
            // comment.setContent(HeiMaUtils.htmlEscape(content));
        });

        return new ModelAndView("detail")
                .addObject("goods", goods);
    }
}
